import re
import time
import datetime

def date2ts(date):
    try:
        return int(time.mktime(time.strptime(date, '%Y-%m-%d')))
    except:
        return int(time.mktime(time.strptime(date, '%Y-%m-%d %H:%M:%S')))
def ts2date(ts):
    return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(ts))
def trans_date_ts(date_str):
    print(date_str,'******************************')
    date = date_str.replace('發表於 ','').replace('半小時前','30 分鐘前')
    # .replace(' PM','').replace(' AM','')
    # 转成时间戳
    now_ts = time.time()
    if '秒前' in date:
        s = int(date.rstrip(' 秒前'))
        ts = now_ts - s
        date = ts2date(ts)
    elif '分鐘前' in date:
        minute = int(date.rstrip(' 分鐘前'))
        ts = now_ts - minute * 60
        date = ts2date(ts)
    elif '小時前' in date:
        hour = int(date.rstrip(' 小時前'))
        ts = now_ts - hour * 3600
        date = ts2date(ts)
    elif '天前' in date:
        hour = int(date.rstrip(' 天前'))
        ts = now_ts - hour * 86400
        date = ts2date(ts)
    elif '昨天' in date:
        new_time = date.lstrip('昨天')
        date = get_before_date(1) + new_time + ":00"
    elif '前天' in date:
        new_time = date.lstrip('前天')
        date = get_before_date(2) + new_time + ":00"
    else:
        format_time = time.strptime(date, '%Y-%m-%d %I:%M %p')
        date = time.strftime('%Y-%m-%d %H:%M:%S', format_time)
    return date, date2ts(date)

def get_before_date(date_cha):
    # date_cha为当天日期的前几天,返回前几天的日期
    # 如当天2018-7-7,date_cha=1,则返回2018-7-6
    today = datetime.date.today()
    oneday = datetime.timedelta(days=date_cha)
    newday = today - oneday
    return str(newday)
if __name__ == '__main__':
    a = '2019-2-21 2:30 PM'
    print(trans_date_ts(a))